#  Copyright (c) 2022. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
#  Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
#  Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
#  Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
#  Vestibulum commodo. Ut rhoncus gravida arcu.

# coding:utf8
from typing import Union
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
# from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.select import Select
from log import logger
import time


class BasePage(object):
    def __init__(self, driver
                 # , base_url=''
                 ):
        """ """
        # self.base_url = base_url
        self.driver = driver
        self.timeout = 30
    
    def i_find_element(self, locator):  # locator为一个元组类型
        
        # return self.driver.find_element(*locator)
        try:
            return self.driver.find_element(*locator)
        except:
            return []
    
    def is_exists_element(self, locator):
        return True if self.i_find_element(locator) else False
    
    def until_find_element(self, locator):
        try:
            WebDriverWait(self.driver, 15).until(lambda driver: driver.find_element(locator).is_display())
            return self.driver.find_element(locator)
        except:
            print("没有找到元素")
            return None
    
    # def open(self, url=''):
    #     url = self.base_url + url
    #     self.driver.get(url)
    
    def get_title(self):
        return self.driver.title
    
    def get_url(self):
        return self.driver.current_url
    
    def hover(self, locator):
        element = self.i_find_element(locator)
        hover = ActionChains(self.driver).move_to_element(element)
        hover.perform()
    
    def wait_element(self, locator):
        try:
            WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(*locator))
        except TimeoutException:
            print('\n * element not found within given time! --> %s' % (locator[1]))
            self.driver.quit()
    
    def clear_key(self, locator):
        """
        重写清空文本框
        """
        time.sleep(3)
        self.i_find_element(locator).clear()
    
    def send_keys(self, locator, value):
        """
        locator: (id, "name")
        """
        
        # self.clear_key(locator)
        self.i_find_element(locator).send_keys(value)
        # time.sleep(1)
    
    def select_combox_index(self, locator, index):
        element = self.i_find_element(locator)
        Select(element).select_by_index(index)  # 索引从0开始
        
    def select_by_value(self, locator, value):
        element = self.i_find_element(locator)
        # Select(element).select_by_value(value)  # 索引从0开始
        Select(element).select_by_visible_text(value)  # 索引从0开始
    
    def click_button(self, locator):
        """
        点击按
        """
        try:
            self.i_find_element(locator).click()
        except:
            pass
    

    
    @staticmethod
    def conversion_ip_to_url(ip):
        return 'http://' + str(ip)
    
    def open_page_from_ip(self, ip):
        url = self.conversion_ip_to_url(ip)
        logger.debug("ip to url: {}".format(url))
        logger.debug("driver getting url: {}".format(url))
        self.driver.get(url)
    
    def max_windows(self):
        self.driver.maximize_window()
    
    def path_other(self):
        """
        not  use
        """
        
        # current_path = os.path.dirname(__file__)  # 获取当前的路径
        # driver_path = os.path.join(current_path, '../driver/chromedriver.exe')  # 当前路径 + chromedriver路径相连
        pass
    
    def sleep(self, nsec):
        time.sleep(nsec)
    
    def init_driver_implicitly(self):
        """
        隐性等待
        """
        
        self.driver.implicitly_wait(self.timeout)
    
    def switch_to_frame(self, frame: Union[str, type]):
        
        frame_str = frame if isinstance(frame, str) else frame.frame
        self.driver.switch_to.default_content();  # 先切换回主框架
        self.driver.switch_to.frame(frame_str); # 然后切换到另一个框架
        
    # def switch_to_frame(self, value):
    #     """
    #     进入iframe页面
    #     """
    #     self.driver.switch_to.frame(value)